<template>
  <div class="app-container customer-div">

    <el-menu :default-active="listQuery.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="my">我负责的</el-menu-item>
      <el-menu-item index="all" v-if="isallSupplierMaterials">全部</el-menu-item>
    </el-menu>

    <div style="margin-top: 20px">
      <el-button
              size="small"
              @click="showDialog()"
              type="primary">
        新增材料
      </el-button>
    </div>
    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="140px">
        <el-form-item label="供应商名称：">
          <el-select
                  clearable
                  v-model="listQuery.supplierId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="remoteMethod3"
                  :loading="loading">
            <el-option
                    v-for="item in supplierList2"
                    :key="item.supplierId"
                    :label="item.supplierName"
                    :value="item.supplierId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品名：">
          <el-input v-model="listQuery.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="牌号：">
          <el-select v-model="listQuery.kingGoodsId" filterable placeholder="请选择" clearable>
            <el-option
                    v-for="item in goodsList"
                    :key="item.kingId"
                    :label="item.goodsSn"
                    :value="item.kingId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间：">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="listQuery.createTime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="最近采购时间：">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="listQuery.lastPurchaseTime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建人：" v-if="listQuery.tab != 'my'">
          <el-select v-model="listQuery.createUserId" placeholder="请选择" clearable>
            <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.realName"
                    :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
                  @click="handleSearchList()"
                  type="primary">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--数据列表-->
    <div class="table-container">
      <el-table
              v-loading="listLoading"
              :data="list"
              border
              style="width: 100%; margin-top: 20px">
        <el-table-column
                label="供应商名称"
                width="400">
          <template slot-scope="scope">
            <el-link @click="toDetail(scope.row)" type="primary">
              {{scope.row.supplierName}}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column
                prop="goodsName"
                label="品名"
                align="center"
                width="100">
        </el-table-column>
        <el-table-column
                prop="goodsSn"
                label="牌号"
                align="center"
                width="200">
        </el-table-column>
        <el-table-column
                align="center"
                prop="purchaseNum"
                label="累计采购量"
                width="180">
        </el-table-column>
        <el-table-column
                label="累计采购金额"
                width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.purchaseAmount}}
          </template>
        </el-table-column>
        <el-table-column
                label="最近采购时间"
                width="150"
                align="center">
          <template slot-scope="scope">
            {{scope.row.lastPurchaseTime}}
          </template>
        </el-table-column>
        <el-table-column
                label="创建时间"
                width="150"
                align="center">
          <template slot-scope="scope">
            {{scope.row.createdTime}}
          </template>
        </el-table-column>
        <el-table-column
                label="创建人"
                width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.createrName}}
          </template>
        </el-table-column>
        <el-table-column
                label="常用"
                width="120"
                align="center">
          <template slot-scope="scope">
            {{scope.row.isCommon==1?'是':'否'}}
          </template>
        </el-table-column>
        <el-table-column
                width="200"
                fixed="right"
                label="操作"
                align="center">
          <template slot-scope="scope">
            <el-button
                    type="text"
                    size="mini"
                    @click="toSupplierInquiry(scope.row)">询价记录
            </el-button>
            <el-button
                    type="text"
                    size="mini"
                    @click="changeIsCommon(scope.row)">{{scope.row.isCommon==1?'取消常用':'设为常用'}}
            </el-button>
            <el-button
                    type="text"
                    size="mini"
                    @click="delRow(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes,prev, pager, next,jumper"
              :current-page.sync="listQuery.pageNum"
              :page-size="listQuery.pageSize"
              :page-sizes="[10,15,20]"
              :total="count">
      </el-pagination>
    </div>

    <!--新增/编辑材料-->
    <el-dialog
            :close-on-click-modal="false"
            :title="title2"
            :beforeClose="handleClose2"
            :visible.sync="dialogVisible2"
            width="600px">
      <el-form :model="materialsForm" size="mini" label-width="120px" :rules="rules" ref="materialsForm">
        <el-form-item label="供应商：" prop="supplierId">
          <el-select
                  v-model="materialsForm.supplierId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="remoteMethod"
                  :loading="loading">
            <el-option
                    v-for="item in supplierList"
                    :key="item.supplierId"
                    :label="item.supplierName"
                    :value="item.supplierId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="材料名称：">
          <el-select
                  clearable
                  v-model="materialsForm.goodsKingId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="remoteMethod2"
                  :loading="loading2">
            <el-option
                    v-for="item in options"
                    :key="item.kingId"
                    :label="item.goodsSn"
                    :value="item.kingId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { getUserOption,orderGoodsList} from '@/api/partner'
  import {supplierListApi,goodsList,supplierGoodsList,supplierGoodsAdd,supplierGoodsDel,setGoods} from '@/api/company'
  import {formatDate} from '@/utils/date';
  import store from '@/store'
  import { mapGetters } from 'vuex'
  const defaultMaterialsForm = {
    supplierId : '',  //供应商ID
    goodsKingId:'',
  };
  const defaultListQuery={
    pageNum: 1,
    pageSize: 10,
    supplierId:'',
    goodsName:'',
    goodsSn:'',
    createTime:null,
    lastPurchaseTime:null,
    createUserId:'',
    tab:'my',
    kingGoodsId:'',
  };
  export default {
    name: "index",
    data(){
      return{
        roles:store.getters.roles ? store.getters.roles : [],
        listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
        list:[],
        count:0,
        listLoading:false,
        dialogVisible2:false,
        title2:'',
        btnLoading2:false,
        materialsForm:JSON.parse(JSON.stringify(defaultMaterialsForm)),
        rules:{
          supplierId:[{required: true, message: '请选择供应商', trigger: 'change'},],
          contactName:[{required: true, message: '请输入联系人姓名', trigger: 'blur'},],
          contactMobile:[{required: true, message: '请输入联系人手机号', trigger: 'blur'},],
        },
        loading:false,
        supplierList:[],
        userOptionList:[],
        options:[],
        loading2:false,
        supplierList2:[],
        goodsList:[],
      }
    },
    computed: {
      ...mapGetters([
        'name',
        'mobile',
        'userId'
      ]),
      isallSupplierMaterials(){
        if(this.roles.indexOf("allSupplierMaterials") != -1){
          return true
        }else{
          return false
        }
      },


    },
    created() {
      this.getListData();
      this.getUserOptionList();
      orderGoodsList().then((res)=>{
        this.goodsList = res.list
      })
    },
    filters: {
      formatTime(time) {
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd')
      },
    },
    methods:{

      //切换常用状态
      changeIsCommon(item){
        setGoods({sgId:item.sgId,isCommon:item.isCommon == 1 ? 0 : 1}).then(()=>{
          this.getListData();
        })

      },
      //去详情页
      toDetail(item){
        let routeData = this.$router.resolve({name:'supplierInfo',query:{id:item.supplierId}});
        window.open(routeData.href);
      },
      //去询价记录页
      toSupplierInquiry(item){
        let routeData = this.$router.resolve({name:'supplierInquiry',query:{supplierId:item.supplierId,supplierName:item.supplierName,tab:this.listQuery.tab}});
        window.open(routeData.href);
      },
      /**
       * 切换选择状态
       */
      handleSelect(key, keyPath){
        this.listQuery.tab = key;
        this.handleSearchList();
      },
      //获取员工下拉选项
      getUserOptionList(){
        getUserOption().then((res)=>{
          this.userOptionList = res;
        })
      },


      //获取供应商列表
      remoteMethod(query) {
        if(query && query!= ''){
          this.loading = true;
          //获取供应产列表
          supplierListApi({tab:this.listQuery.tab,supplierName:query,pageNum:1,pageSize:1000}).then(response => {
            this.supplierList = response.list;
            this.loading = false;
          }).catch(()=>{
            this.loading = false;
          });

        }
      },
      //获取供应商列表
      remoteMethod3(query) {
        if(query && query!= ''){
          this.loading3 = true;
          //获取供应产列表
          supplierListApi({tab:this.listQuery.tab,supplierName:query,pageNum:1,pageSize:1000}).then(response => {
            this.supplierList2 = response.list;
            this.loading3 = false;
          }).catch(()=>{
            this.loading3 = false;
          });

        }
      },
      //获取商品列表
      remoteMethod2(query) {
        if (query !== '') {
          this.loading2 = true;
          goodsList({keywords:query}).then((res)=>{
            this.options = res.list;
            this.loading2 = false;
          }).catch(()=>{
            this.loading2 = false;
          });
        } else {
          this.options = [];
        }
      },

      handleSearchList(){
        this.listQuery.pageNum = 1;
        this.getListData();
      },
      //获取列表
      getListData(){
        this.listLoading = true;
        let data = JSON.parse(JSON.stringify(this.listQuery));
        supplierGoodsList(data).then((res)=>{
          this.list = res.list;
          this.count = res.count;
          this.listLoading = false;
        }).catch(()=>{
          this.listLoading = false;
        })
      },

      handleSizeChange(val){
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getListData();
      },
      handleCurrentChange(val){
        this.listQuery.pageNum = val;
        this.getListData();
      },


      //删除记录
      delRow(item){
        this.$confirm('确定删除这条记录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          supplierGoodsDel({sgId:item.sgId}).then(()=>{
            this.getListData();
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      //显示新增/编辑
      showDialog(){
        this.title2 = '新增材料';
        this.dialogVisible2 = true;this.options=[];
        this.materialsForm = JSON.parse(JSON.stringify(defaultMaterialsForm));
      },

      //关闭弹窗
      handleClose2(){
        this.$refs.materialsForm.clearValidate();
        this.dialogVisible2 = false;
        this.btnLoading2 = false;
        this.supplierList = [];
        this.options = [];
      },

      //提交材料
      handleConfirm2(){
        this.$refs.materialsForm.validate((valid) => {
          if (valid) {
            this.btnLoading2 = true;
            supplierGoodsAdd(this.materialsForm).then((res)=>{
              this.btnLoading2 = false;
              this.handleClose2();
              this.getListData();
            })
          }
        })
      },
    },
  }
</script>

<style scoped lang="scss">
  .avatar-uploader{
    margin-bottom:10px;
    display: inline-block;
    width:80px;
    height:80px;
    border:1px solid #DCDFE6;
    text-align: center;
    line-height: 80px;
  }
</style>
